package g360.WebXpdlValidation;

import java.util.ArrayList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ErrorCollector implements ErrorHandler
{
    ArrayList<String> messages = new ArrayList<String>();

    public ErrorCollector()
    {

    }

    /** Warning. */
    public void warning(SAXParseException ex) throws SAXException
    {
    	appendErrorMessage("Warning", ex);
    } // warning(SAXParseException)

    /** Error. */
    public void error(SAXParseException ex) throws SAXException {
    	appendErrorMessage("Error", ex);
    } // error(SAXParseException)

    /** Fatal error. */
    public void fatalError(SAXParseException ex) throws SAXException {
    	appendErrorMessage("Fatal Error", ex);
        throw ex;
    } // fatalError(SAXParseException)

    /** Composes the error message. */
    protected void appendErrorMessage(String type, SAXParseException ex)
    {
    	this.appendMessage(composeErrorMessage(type, ex));
    }

    protected String composeErrorMessage(String type, SAXParseException ex)
    {
    	String result = "";
        String systemId = ex.getSystemId();
        if (systemId != null)
        {
            int index = systemId.lastIndexOf('/');
            if (index != -1)
                systemId = systemId.substring(index + 1);
        }
        else
        	systemId = "";

    	result = "[" + type + "] " + systemId + ":" + ex.getLineNumber() + ":" + ex.getColumnNumber() + ": " + ex.getMessage();
    	return result;

    } // composeErrorMessage(String,SAXParseException)

    public void appendExceptionReport(Exception ex, String messagePrefix)
    {
        String message = messagePrefix + " - " + ex.getMessage();
        this.appendMessage(message);
        System.err.println(message);
        if (ex instanceof SAXException)
        {
            Exception se = ((SAXException)ex).getException();
            if (se != null) ex = se;
        }
        ex.printStackTrace(System.err);

    }



    public void clearMessages()
    {
    	this.messages.clear();
    }

    protected void appendMessage(String message)
    {
    	if (message != null)
    	{
            this.messages.add(message);
    	}
    }

    public ArrayList<String> getMessages()
    {
    	return this.messages;
    }

}